﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.Diagnostics;
using System.Windows.Threading;

namespace System.Windows.Media.DirectShow
{
    internal class SystemClock : IReferenceClock
    {

        private TimeSpan infinite = new TimeSpan(-1);
        private FilterGraph graph;

        public SystemClock(FilterGraph graph)
        {
            this.graph = graph;   
        }

        #region IReferenceClock Members

        public TimeSpan GetTime()
        {
            return TimeSpan.FromMilliseconds(Environment.TickCount);
        }

        public void AdviseTime(TimeSpan time, System.Threading.TimerCallback handler, object state)
        {
            graph.Dispatcher.BeginInvoke(() =>
            {
                TimeSpan due = time - GetTime();
                if (due.Ticks < 0)
                    due = TimeSpan.Zero;
                
                //Debug.WriteLine("due {0}", due);
                
                DispatcherTimer timer = new DispatcherTimer();
                timer.Interval = due;
                timer.Tick += delegate
                {
                    timer.Stop();
                    handler(state);
                };
                timer.Start();
            });
        }

        #endregion
    }
}
